import easygui as eg
from database import Database


def show_user_management(db, current_user):
    while True:
        # 获取用户列表
        users = db.execute_query("""
            SELECT u.UserID, u.Username, u.RealName, u.UserType, 
                   CASE WHEN u.Status = 1 THEN '启用' ELSE '禁用' END AS StatusText
            FROM Users u
            ORDER BY u.UserType, u.Username
        """)

        if not users:
            eg.msgbox("没有用户数据", "用户管理")
            break

        # 格式化显示
        user_list = [
            f"ID:{u['UserID']} | 用户名:{u['Username']} | 姓名:{u['RealName'] or '无'} | "
            f"类型:{get_user_type_name(u['UserType'])} | 状态:{u['StatusText']}"
            for u in users
        ]

        # 添加操作选项
        user_list.extend(
            ["", "=== 操作选项 ===", "1. 添加用户", "2. 编辑用户", "3. 删除用户", "4. 权限管理", "5. 返回"])

        choice = eg.choicebox("用户管理系统", "用户管理", user_list)

        if not choice or choice == "5. 返回":
            break

        if choice == "1. 添加用户":
            add_user(db)
        elif choice == "2. 编辑用户":
            user_id = get_id_from_choice(choice)
            if user_id:
                edit_user(db, user_id)
        elif choice == "3. 删除用户":
            user_id = get_id_from_choice(choice)
            if user_id:
                delete_user(db, user_id)
        elif choice == "4. 权限管理":
            user_id = get_id_from_choice(choice)
            if user_id:
                manage_permissions(db, user_id)


def get_id_from_choice(choice):
    if "ID:" not in choice:
        return None
    return int(choice.split("ID:")[1].split("|")[0].strip())


def get_user_type_name(user_type):
    types = {'admin': '管理员', 'guide': '导游', 'tourist': '游客'}
    return types.get(user_type, user_type)


def add_user(db):
    fields = ["用户名*", "密码*", "确认密码*", "用户类型(admin/guide/tourist)*", "真实姓名", "电子邮箱", "联系电话"]
    values = eg.multenterbox("添加新用户", "用户管理", fields)

    if not values:
        return

    username, password, confirm, user_type, realname, email, phone = values

    # 验证必填字段
    if not all([username, password, confirm, user_type]):
        eg.msgbox("带*的字段为必填项", "错误")
        return

    if password != confirm:
        eg.msgbox("两次输入的密码不一致", "错误")
        return

    if user_type not in ['admin', 'guide', 'tourist']:
        eg.msgbox("用户类型必须是admin/guide/tourist", "错误")
        return

    try:
        # 检查用户名是否已存在
        if db.execute_query("SELECT 1 FROM Users WHERE Username = ?", (username,)):
            eg.msgbox("用户名已存在", "错误")
            return

        # 添加用户
        hashed_pw = Database.hash_password(password)
        db.execute_query("""
            INSERT INTO Users (Username, Password, UserType, RealName, Email, Phone, Status)
            VALUES (?, ?, ?, ?, ?, ?, 1)
        """, (username, hashed_pw, user_type, realname, email, phone), False)

        # 如果是导游或游客，添加额外信息
        user_id = db.execute_query("SELECT SCOPE_IDENTITY() AS id")[0]['id']

        if user_type == 'guide':
            add_guide_info(db, user_id)
        elif user_type == 'tourist':
            add_tourist_info(db, user_id)

        eg.msgbox("用户添加成功", "成功")
    except Exception as e:
        eg.msgbox(f"添加用户失败: {str(e)}", "错误")


def edit_user(db, user_id):
    user = db.execute_query("SELECT * FROM Users WHERE UserID = ?", (user_id,))[0]

    fields = ["用户名", "用户类型", "真实姓名", "电子邮箱", "联系电话", "状态(1启用/0禁用)"]
    values = [
        user['Username'],
        user['UserType'],
        user['RealName'] or "",
        user['Email'] or "",
        user['Phone'] or "",
        str(user['Status'])
    ]

    new_values = eg.multenterbox("编辑用户信息", "用户管理", fields, values)

    if not new_values:
        return

    try:
        db.execute_query("""
            UPDATE Users SET 
                Username = ?, UserType = ?, RealName = ?, 
                Email = ?, Phone = ?, Status = ?
            WHERE UserID = ?
        """, (*new_values, user_id), False)
        eg.msgbox("用户信息更新成功", "成功")
    except Exception as e:
        eg.msgbox(f"更新失败: {str(e)}", "错误")


def delete_user(db, user_id):
    if not eg.ynbox("确定要删除这个用户吗？", "确认删除"):
        return

    try:
        # 先删除关联数据
        user_type = db.execute_query("SELECT UserType FROM Users WHERE UserID = ?", (user_id,))[0]['UserType']

        if user_type == 'guide':
            db.execute_query("DELETE FROM Guides WHERE UserID = ?", (user_id,), False)
        elif user_type == 'tourist':
            db.execute_query("DELETE FROM Tourists WHERE UserID = ?", (user_id,), False)

        # 删除用户
        db.execute_query("DELETE FROM Users WHERE UserID = ?", (user_id,), False)
        eg.msgbox("用户删除成功", "成功")
    except Exception as e:
        eg.msgbox(f"删除失败: {str(e)}", "错误")


def manage_permissions(db, user_id):
    # 获取所有权限
    permissions = db.execute_query("SELECT * FROM Permissions")
    # 获取用户已有权限
    user_perms = db.execute_query("""
        SELECT p.PermissionID FROM UserPermissions up
        JOIN Permissions p ON up.PermissionID = p.PermissionID
        WHERE up.UserID = ?
    """, (user_id,))
    user_perm_ids = [p['PermissionID'] for p in user_perms]

    # 创建多选列表
    choices = []
    for p in permissions:
        choices.append([p['PermissionName'], p['PermissionID'] in user_perm_ids])

    selected = eg.multchoicebox("选择权限", "权限管理", [c[0] for c in choices], choices)

    if selected is None:
        return

    try:
        # 先清除原有权限
        db.execute_query("DELETE FROM UserPermissions WHERE UserID = ?", (user_id,), False)

        # 添加新权限
        for perm in permissions:
            if perm['PermissionName'] in selected:
                db.execute_query("""
                    INSERT INTO UserPermissions (UserID, PermissionID)
                    VALUES (?, ?)
                """, (user_id, perm['PermissionID']), False)

        eg.msgbox("权限更新成功", "成功")
    except Exception as e:
        eg.msgbox(f"权限更新失败: {str(e)}", "错误")


def add_guide_info(db, user_id):
    fields = ["导游证号*", "性别", "年龄", "从业年限", "专长", "简介"]
    values = eg.multenterbox("添加导游信息", "导游信息", fields)

    if not values:
        return

    license_no, gender, age, exp, specialty, intro = values

    if not license_no:
        eg.msgbox("导游证号为必填项", "错误")
        return

    try:
        db.execute_query("""
            INSERT INTO Guides (UserID, LicenseNumber, Gender, Age, Experience, Specialty, Introduction)
            VALUES (?, ?, ?, ?, ?, ?, ?)
        """, (user_id, license_no, gender, age, exp, specialty, intro), False)
    except Exception as e:
        eg.msgbox(f"添加导游信息失败: {str(e)}", "错误")


def add_tourist_info(db, user_id):
    fields = ["身份证号*", "性别", "年龄", "地址", "紧急联系人", "紧急联系电话"]
    values = eg.multenterbox("添加游客信息", "游客信息", fields)

    if not values:
        return

    id_no, gender, age, address, emergency_contact, emergency_phone = values

    if not id_no:
        eg.msgbox("身份证号为必填项", "错误")
        return

    try:
        db.execute_query("""
            INSERT INTO Tourists (UserID, IDNumber, Gender, Age, Address, EmergencyContact, EmergencyPhone)
            VALUES (?, ?, ?, ?, ?, ?, ?)
        """, (user_id, id_no, gender, age, address, emergency_contact, emergency_phone), False)
    except Exception as e:
        eg.msgbox(f"添加游客信息失败: {str(e)}", "错误")